//
//  BusinessMemberfindIntegralListViewController.m
//  HAODE
//
//  Created by panquanReabam.com on 15/9/26.
//  Copyright (c) 2015年 reabam.com. All rights reserved.
//

#import "BusinessMemberAddressViewController.h"
#import "OrderDetailViewController.h"
#import "InstallConfirmViewController.h"
#import "huiyuandengjiViewController.h"
#import "shouyingViewController.h"
#import "MJRefresh.h"
#import "indIntegralListCell.h"
#import "MemberAddressCell.h"
#import "addAddressViewController.h"
#import "editAddressViewController.h"
#import "UIImage+RTTint.h"
@interface BusinessMemberAddressViewController ()<MBProgressHUDDelegate,UIGestureRecognizerDelegate,UINavigationControllerDelegate,UITextFieldDelegate,UISearchBarDelegate,UIAlertViewDelegate>
@property (strong, nonatomic)NSString *areaValue;
@property (strong, nonatomic)NSString*cityValue;
@property (retain, nonatomic)NSString*sats;
@property (retain, nonatomic)NSString*orderSort;

@end

@implementation BusinessMemberAddressViewController

{
    UISearchBar *search;
    HAODEsingleton* commdity;
    MJRefreshHeaderView* _header;
    MJRefreshFooterView* _footer;
    NSMutableArray* name;
    NSMutableArray* phone;
    NSMutableArray* address;
    NSMutableArray*provinceName;
    NSMutableArray* isDefault;
    NSMutableArray* addressId;
    NSMutableArray* cityName;
    NSMutableArray*regionName;
    BOOL saveAccount;
    BOOL saveAccount1;
    NSString *result;
    int pageNumber;
    MBProgressHUD *progressHud;
    UIView* backview1;
    UIScrollView*myscrollView;
    NSString* sous;
    NSString*meiyousuos;
    UIView*view3;
    NSString*TotalCount;
    
}
@synthesize alt = alt;

-(void)BackAction:(UIButton *)sender{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}
- (void)viewDidDisappear:(BOOL)animated

{
    
    [super viewDidDisappear:animated];
    self.navigationController.delegate = nil;
    
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[self rdv_tabBarController] setTabBarHidden:YES];
    self.navigationController.navigationBarHidden=NO;
        self.navigationController.navigationBar.barStyle = UIBaselineAdjustmentNone;
    UILabel *lineLabel=[[UILabel alloc] initWithFrame:CGRectMake(0, 43,ScreenWidth, 1)];
    [lineLabel setBackgroundColor:[UIColor colorWithRed:238.0/255.0 green:238.0/255.0 blue:238.0/255.0 alpha:1.0]];
    [self.navigationController.navigationBar addSubview:lineLabel];
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setBarTintColor:Color];
    
    UIImage* backImage = [UIImage imageNamed:@"fanhui"];
    CGRect backframe = CGRectMake(0,0,30,30);
    UIButton* backButton= [[UIButton alloc] initWithFrame:backframe];
    [backButton setBackgroundImage:backImage forState:UIControlStateNormal];
    backButton.titleLabel.textAlignment=NSTextAlignmentLeft;
    [backButton addTarget:self action:@selector(BackAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem* leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    self.navigationItem.leftBarButtonItem = leftBarButtonItem;
    self.navigationController.delegate = self;
    self.navigationController.interactivePopGestureRecognizer.enabled = YES;
    self.navigationController.interactivePopGestureRecognizer.delegate = self;
    
    [self.navigationController.navigationBar setBackgroundImage:nil forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [[UIImage alloc] init];
    
    self.title=@"地址管理";
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor blackColor],
                                                                     UITextAttributeTextColor,
                                                                     [UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:1],
                                                                     UITextAttributeTextShadowColor,
                                                                     [NSValue valueWithUIOffset:UIOffsetMake(0, 0)],
                                                                     UITextAttributeTextShadowOffset,
                                                                     [UIFont fontWithName:@"Helvetica Neue" size:tetlefot],
                                                                     UITextAttributeFont,nil]];
    
    
    [self add];
    
}



- (void)viewDidLoad
{
    
    [super viewDidLoad];
    
    commdity=[HAODEsingleton shared];
    
    
    
    _table.delegate=self;
    _table.dataSource=self;
    _table.separatorStyle=UITableViewCellSeparatorStyleNone;
    
    
    UIButton*addBtn=[[UIButton alloc]initWithFrame:CGRectMake(0, ScreenHeight-48, ScreenWidth, 48)];
    [addBtn setTitle:@"+  新增提货地址" forState:UIControlStateNormal];
    addBtn.backgroundColor=luseColor;
    [addBtn addTarget:self action:@selector(adds:) forControlEvents:UIControlEventTouchUpInside];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    NSMutableAttributedString *AttributedStr = [[NSMutableAttributedString alloc]initWithString:@"+  新增提货地址"];
    
    [AttributedStr addAttribute:NSFontAttributeName
     
                          value:[UIFont systemFontOfSize:24]
     
                          range:NSMakeRange(0, 1)];
    
    [AttributedStr addAttribute:NSForegroundColorAttributeName
     
                          value:[UIColor whiteColor]
     
                          range:NSMakeRange(0, 1)];
    addBtn.titleLabel.attributedText = AttributedStr;
    [self.view addSubview:addBtn];
    
}

-(void)adds:(UIButton*)sender{

    commdity.gengxin=@"";
    addAddressViewController *detailViewController = [[addAddressViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];

}

-(void)add{

    
    pageNumber = 1;
    
   
    name= [[NSMutableArray alloc] init];
    phone= [[NSMutableArray alloc] init];
    address= [[NSMutableArray alloc] init];
    provinceName= [[NSMutableArray alloc] init];
    isDefault= [[NSMutableArray alloc] init];
    addressId= [[NSMutableArray alloc] init];
    cityName= [[NSMutableArray alloc] init];
    regionName= [[NSMutableArray alloc] init];
    commdity=[HAODEsingleton shared];
    
  
    
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
    [param setValue:@"1" forKey:@"pageIndex"];
    [param setValue:@"20" forKey:@"pageSize"];
    [param setValue:commdity.memberId forKey:@"memberId"];
    
    
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    
    [HttpRequest requestData:@"Business/Member/Address" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                
                NSMutableArray* arrr=[[NSMutableArray alloc]init];
                
                arrr=[severDataDict.dataDict objectForKey:@"DataLine"];
                TotalCount=[severDataDict.dataDict objectForKey:@"totalIntegral"];
                
                
                for (NSDictionary* dicc in arrr )
                {
                    [address addObject:[dicc valueForKey:@"address"]];
                    [addressId addObject:[dicc valueForKey:@"addressId"]];
                    [cityName addObject:[dicc valueForKey:@"cityName"]];
                    [isDefault addObject:[dicc valueForKey:@"isDefault"]];
                    [name addObject:[dicc valueForKey:@"name"]];
                    [phone addObject:[dicc valueForKey:@"phone"]];
                    [provinceName addObject:[dicc valueForKey:@"provinceName"]];
                    [regionName addObject:[dicc valueForKey:@"regionName"]];


                    
                }
                [_table reloadData];
                
                
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    
   

    
    
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [addressId count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    MemberAddressCell* cell = (MemberAddressCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil)
    {
        NSArray* nib = [[NSBundle mainBundle] loadNibNamed:@"MemberAddressCell" owner:self options:nil];
        cell = [nib objectAtIndex:0];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    cell.name1=[NSString stringWithFormat:@"%@",[name objectAtIndex:indexPath.row]];
    cell.phone1=[NSString stringWithFormat:@"%@",[phone objectAtIndex:indexPath.row]];
    cell.address1=[NSString stringWithFormat:@"%@",[address objectAtIndex:indexPath.row]];
    cell.sheng=[NSString stringWithFormat:@"%@",[provinceName objectAtIndex:indexPath.row]];
    cell.shi=[NSString stringWithFormat:@"%@",[cityName objectAtIndex:indexPath.row]];
     cell.qu=[NSString stringWithFormat:@"%@",[regionName objectAtIndex:indexPath.row]];
    cell.isDefault1=[NSString stringWithFormat:@"%@",[isDefault objectAtIndex:indexPath.row]];
    cell.addid=[NSString stringWithFormat:@"%@",[addressId objectAtIndex:indexPath.row]];
    cell.name.text=[name objectAtIndex:indexPath.row];
    cell.address.text=[NSString stringWithFormat:@"%@%@%@%@",[provinceName objectAtIndex:indexPath.row],[cityName objectAtIndex:indexPath.row],     [regionName objectAtIndex:indexPath.row],[address objectAtIndex:indexPath.row]];
    cell.phone.text=[NSString stringWithFormat:@"%@",  [phone objectAtIndex:indexPath.row]];
    
    if ([[isDefault objectAtIndex:indexPath.row]intValue]==1) {
//        UIImage *img=[UIImage imageNamed:@"sheweimoren_hight"];
//        
//        UIImage *tinted = [img rt_tintedImageWithColor:luseColor ];
//        
//        [cell.moren setBackgroundImage:tinted forState:UIControlStateNormal];
//        UIImage *img=[UIImage imageNamed:@"yanjing_hights"];
//        
//        UIImage *tinted = [img rt_tintedImageWithColor:luseColor ];
          [cell.moren setImage:[UIImage imageNamed:@"jizhumima_hight"] forState:UIControlStateNormal];
//        [cell.moren setImage:tinted forState:UIControlStateNormal];
    
    }
    [cell.moren addTarget:self action:@selector(moren:) forControlEvents:UIControlEventTouchUpInside];
    UIImageView *_xianview = [[UIImageView alloc]initWithFrame:CGRectMake(15,97-0.5, ScreenWidth-30, 0.5)];
    _xianview.image=[UIImage imageNamed:@"hengxian"];
    
    [cell.contentView addSubview:_xianview];
    [cell.shanchu addTarget:self action:@selector(shanchu:) forControlEvents:UIControlEventTouchUpInside];
    [cell.bianji addTarget:self action:@selector(bianji:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    

        
        commdity.consigneeAddr=[NSString stringWithFormat:@"%@%@%@%@",provinceName [indexPath.row],cityName [indexPath.row],     regionName[indexPath.row],address [indexPath.row]];

        commdity.consigneeName=name[indexPath.row];
        commdity.consigneePhone=phone[indexPath.row];
        
        
        if ([commdity.addhuiyuanViewController isEqualToString:@"选择"]) {
            
     
            NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
            NSString* Token = [user objectForKey:@"tokenId"];
            if (Token ==nil) {
                Token=@"dd";
            }
            NSMutableDictionary *param = [NSMutableDictionary new];
            [param setValue:Token forKey:@"tokenId"];
            
            [param setValue:addressId[indexPath.row] forKey:@"addressId"];
            
            NSLog(@"====%@",param);
            [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
            
            
            [HttpRequest requestData:@"Business/Member/setDefaultAddress" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
                if (isSuccess) {
                    
                    NSLog(@"====%@",severDataDict.dataDict);
                    if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                        [Global hideProgressHUDInternal:self.view];
                        
                        
                        
                          [self.navigationController popViewControllerAnimated:YES];
                        
                        
                        
                    }else{
                        [Global hideProgressHUDInternal:self.view];
                        
                    }
                    
                }
                else
                {
                    [Global hideProgressHUDInternal:self.view];
                    
                    [Global showTextHudSub:@"连接失败" view:self.view];
                }
                
            }];
            

          
            
            
        }else{
            
            
            
    }
    
    
}

-(void)bianji:(UIButton*)sender{
    
    UIButton* button=(UIButton * )sender;
    MemberAddressCell* cell=(MemberAddressCell* )button.superview.superview;
    commdity.code=cell.addid;
    
    commdity.title=cell.name1;
    commdity.isDefault=cell.isDefault1;
    commdity.Phone=cell.phone1;
    commdity.adress=cell.address1;
    commdity.ProvinceName=cell.sheng;
    commdity.CityName=cell.shi;
    commdity.ProvinceName=cell.sheng;
    commdity.RegionName=cell.qu;
    
  
    editAddressViewController *detailViewController = [[editAddressViewController alloc] init];
    [self.navigationController pushViewController:detailViewController animated:YES];
    
}
-(void)shanchu:(UIButton*)sender{
    
    
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"确认删除" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消" ,nil];
    [alert show];

    
    
    UIButton* button=(UIButton * )sender;
    MemberAddressCell* cell=(MemberAddressCell* )button.superview.superview;
 
    commdity.code=cell.addid;

}




#pragma mark UIActionSheetDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    if (buttonIndex == 0) {
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString* Token = [user objectForKey:@"tokenId"];
        if (Token ==nil) {
            Token=@"dd";
        }
        NSMutableDictionary *param = [NSMutableDictionary new];
        [param setValue:Token forKey:@"tokenId"];
        [param setValue:@"D" forKey:@"editType"];
        [param setValue:commdity.memberId forKey:@"memberId"];
        [param setValue:commdity.code forKey:@"addressId"];
        NSLog(@"====%@",param);
        [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
        
        
        [HttpRequest requestData:@"Business/Member/editAddress" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
            if (isSuccess) {
                
                NSLog(@"====%@",severDataDict.dataDict);
                if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                    [Global hideProgressHUDInternal:self.view];
                    
                    [self add];
                    
                    
                    
                    
                    
                }else{
                    [Global hideProgressHUDInternal:self.view];
                    
                }
                
            }
            else
            {
                [Global hideProgressHUDInternal:self.view];
                
                [Global showTextHudSub:@"连接失败" view:self.view];
            }
            
        }];

    } else if (buttonIndex == 1) {
       
    
    
    
    }
}





    




-(void)moren:(UIButton*)sender{
    
    
    
    UIButton* button=(UIButton * )sender;
    MemberAddressCell* cell=(MemberAddressCell* )button.superview.superview;
   

    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString* Token = [user objectForKey:@"tokenId"];
    if (Token ==nil) {
        Token=@"dd";
    }
    NSMutableDictionary *param = [NSMutableDictionary new];
    [param setValue:Token forKey:@"tokenId"];
   
    [param setValue:cell.addid forKey:@"addressId"];
    
     NSLog(@"====%@",param);
    [Global showIndeterminateHudSub:@"加载中，请稍后。。。" delay:30 view:self.view];
    
    
    [HttpRequest requestData:@"Business/Member/setDefaultAddress" params:param success:^(BOOL isSuccess, SeverData *severDataDict) {
        if (isSuccess) {
            
            NSLog(@"====%@",severDataDict.dataDict);
            if ([[severDataDict.dataDict objectForKey:@"ResultInt"] integerValue]==0) {
                [Global hideProgressHUDInternal:self.view];
                commdity.gengxin=@"";
                [self add];
         
                
                
                
                
            }else{
                [Global hideProgressHUDInternal:self.view];
                
            }
            
        }
        else
        {
            [Global hideProgressHUDInternal:self.view];
            
            [Global showTextHudSub:@"连接失败" view:self.view];
        }
        
    }];
    

}



- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 150;
}

#pragma mark - Table view delegate

- (void)showAlertWait
{
    alt = [[UIAlertView alloc] initWithTitle:@"网络不稳定 ！" message:@"请确认网络" delegate:self cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
    
}

- (void)showAlertMessage:(NSString *)msg
{
    alt = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:msg delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
    [alt show];
    
    [self performSelector:@selector(hideAlert) withObject:nil afterDelay:1.0f];
}
- (void)hideAlert
{
    if (alt != nil)
    {
        [alt dismissWithClickedButtonIndex:0 animated:YES];
        alt = nil;
    }
}

@end

